package com.acme.service.email;

import com.acme.domain.email.Email;
import com.acme.domain.email.Queue;
import com.acme.domain.email.impl.QueueImpl;

public class EmailService implements Runnable {
    private Queue queue = new QueueImpl();
    private Thread t;
    private static EmailService instance = new EmailService();

    public EmailService() {
        t = new Thread(this);
        t.start();

    }

    public static EmailService getEmailService() {
        return instance;
    }

    public void sendNotificationEmail(Email email) {
        if (!(queue.isQueueClosed())) {
            queue.addEmail(email);
        }
    }

    @Override
    public void run() {
        while (!(t.isInterrupted())) {
            while (!(queue.isEmpty())) {
                System.out.println(queue.getEmail(0));
            }

        }
    }

    public void close() {
        synchronized (queue) {
            queue.setQueueClosed(true);
            if (!(queue.isEmpty())) {
                try {
                    queue.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            t.interrupt();
            System.out.println("OK");
        }
    }
}
